package com.softWang.common.service.sms.aliyun;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.softWang.common.exception.LogicException;
import com.softWang.common.service.sms.SmsSendInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component("aliYunSmsSendImpl")
@ConditionalOnProperty(name = "sms.impl", havingValue = "aliYunSmsSendImpl")
public class AliYunSmsSendImpl implements SmsSendInterface {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private AliYunConfig aliYunConfig;
    @Resource
    private ObjectMapper objectMapper;

    private Client client;

    @PostConstruct
    public void init(){
        try {
            Config config = new Config()
                    // 配置 AccessKey ID。
                    .setAccessKeyId(aliYunConfig.getAccessKey())
                    // 配置 AccessKey Secret。
                    .setAccessKeySecret(aliYunConfig.getAccessSecret());
            // 配置 Endpoint
            config.endpoint = aliYunConfig.getEndpoint();

            this.client = new Client(config);
            logger.info("初始化阿里云短信服务成功");
        }catch (Exception e){
            logger.error("初始化阿里云短信服务失败:",e);
        }
    }
    @Override
    public void sendSms(String mobile, String templateCode, LinkedHashMap<String, Object> templateParam) throws Exception {
        String content = null;
        if(templateParam != null && templateParam.size() > 0){
            content = objectMapper.writeValueAsString(templateParam);
        }
        // 构造请求对象，请填入请求参数值
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(mobile)
                .setSignName(aliYunConfig.getSignName())
                .setTemplateCode(templateCode);
        if(content != null ) {
            sendSmsRequest.setTemplateParam(content);
        }

        // 获取响应对象
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        if (sendSmsResponse.getBody().getCode() == null || !sendSmsResponse.getBody().getCode().equals("OK")) {
            logger.error("阿里云短信发送失败:" + sendSmsResponse.getBody().getCode() +"," +sendSmsResponse.getBody().getMessage());
            throw new LogicException("短信发送失败:" + sendSmsResponse.getBody().getCode() +"," +sendSmsResponse.getBody().getMessage());
        }
    }

    @Override
    public void sendSmsBatch(List<String> mobiles, String templateCode, LinkedHashMap<String, Object> templateParam) throws Exception {
        int blockSize = 50;
        int blockNum = mobiles.size() / blockSize + 1;
        for (int i = 0; i < blockNum; i++) {
            int start = i * blockSize;
            int end = (i + 1) * blockSize > mobiles.size() ? mobiles.size() : (i + 1) * blockSize;
            List<String> blockMobiles = mobiles.subList(start, end);

            String phones = String.join(",", blockMobiles);
            sendSms(phones, templateCode, templateParam);
        }
    }
}
